package me.zhengjie.config.utils;

import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class PDFUtil {

    private static final String OUT_PUT_PDF_PATH = "/home/eladmin/file/html/"; //pdf文件的存放路径（Linux）
    //private static final String OUT_PUT_PDF_PATH = "d:/pdf/"; //pdf文件的存放路径（windows）

    /**
     * @Title 网页转存为PDF文件
     * @param url 链接地址
     * @param outputFileName 转存的PDF文件名
     */
    public static void urlToPdf(String url, String outputFileName) {
        try {
            String folder = outputFileName.substring(0, 6);
            //String outputFile = OUT_PUT_PDF_PATH + folder +"/"+ outputFileName;
            String outputFile =  outputFileName;
            java.io.File targetFile = new java.io.File(outputFile);
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs(); // 创建父级文件路径
            }
            OutputStream os = new FileOutputStream(outputFile);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);

            SharedContext sharedContext = renderer.getSharedContext();
            // 解决base64图片支持问题
            sharedContext.setReplacedElementFactory(new B64ImgReplacedElementFactory());
            sharedContext.getTextRenderer().setSmoothingThreshold(0);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont("/usr/share/fonts/chinese/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); //Linux
//            fontResolver.addFont("c:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //windows
            renderer.layout();
            renderer.createPDF(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //urlToPdf("http://wx.drzh-atmr.cn/file/html/20211203/916316230908903424.html", "201905098888888.pdf");
        //urlToPdf("http://wx.drzh-atmr.cn/file/html/20211225/924411097165856768.html", "d://123456.pdf");
        urlToPdf("http://wx.drzh-atmr.cn/file/html/20211226/924703412979761152.html", "d://123456.pdf");
    }
}
